import router from '@/router'
import { cloneDeep } from 'lodash'
import { defineStore } from 'pinia'
import type { RouteLocationMatched, RouteRecordRaw } from 'vue-router'

// 判断当前路由是否是home首页路由
export const isHome = (route: RouteLocationMatched) => {
  const name = route && route.name
  if (!name) {
    return false
  }
  return (
    name.toString().trim().toLocaleLowerCase() === 'Home'.toLocaleLowerCase()
  )
}

export const navStateStore = defineStore('navStata', {
  state: (): any => {
    return {
      // 存储滚动栏访问的访问的路由
      matched: [],
      //   存储存放滚动条的数据
      scroolList: [
        {
          path: '/home',
          meta: { title: '首页', isShow: true, isShowCri: true }
        }
      ]
    }
  },
  actions: {
    // 获取访问路由的信息
    getBreadcrumb(levelList: any, route: any, type: string) {
      // only show routes with meta.title
      this.matched = cloneDeep(route.matched).filter(
        (item: any) => item.meta && item.meta.title
      )
      const first = this.matched[0]
      if (!isHome(first)) {
        this.matched = [
          {
            path: '/home',
            meta: { title: '首页', isShow: true, isShowCri: true }
          }
        ].concat(this.matched)
      }
    },
    // 给滚动列表添加数据的方法
    getScroolList(route: any) {
      this.scroolList = cloneDeep(route.matched).filter(
        (item: any) => item.meta && item.meta.isShowCri
      )
      const first = this.scroolList[0]
      if (!isHome(first)) {
        this.scroolList = [].concat(this.scroolList)
      }
    },
    // 点击左侧菜单向数组里添加数据
    addMeunItem(item: any) {
      // 判断是否有子路由的个数为1且子路由的path为""
      if (
        item.children &&
        item.children.length === 1 &&
        item.children[0].path === ''
      ) {
        item.children[0].isShowCri = true
        this.scroolList.push(item.children[0])
      } else {
        // 给每一项加上一个isShowCri变量，来判断点击的是哪一个
        this.scroolList.map((itemView: any) => {
          itemView.meta.isShowCri = false
          if (itemView.path === item.path) {
            itemView.meta.isShowCri = true
          }
        })

        const res = this.scroolList.every((itemRoute: any) => {
          return item.path !== itemRoute.path
        })
        if (res) {
          item.meta.isShowCri = true
          this.scroolList.push(item)
        }
      }
    },

    // 点击删除删除当前项
    closeItem(item: any) {
      this.scroolList = this.scroolList.filter((routeItem: any) => {
        return routeItem !== item
      })
      // 点击删除的时候要判断删除的额是否是当前访问的页面
      if (item.meta.isShowCri) {
        // 点击的是当前访问的项
        // console.log(this.scroolList[this.scroolList.length - 1])
        this.scroolList[this.scroolList.length - 1].meta.isShowCri = true
        router.push(this.scroolList[this.scroolList.length - 1].path)
      }
    },
    // 点击删除修改面包屑的数据
    delBrandItem(item: any) {}
  }
})
